﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Text;

namespace Common.Helpers
{
    /// <summary>
    /// Author: Mike Barksdale
    /// Helper classes for xml conversion methods.
    /// </summary>
    public static class XmlConversionHelper
    {
        /// <summary>
        /// Author: Mike Barksdale
        /// Takes an XML string and returns an inferred XSD string.
        /// </summary>
        /// <param name="xml">The xml for the xsd</param>
        /// <returns>String representing the inferred XSD from the XML string</returns>
        public static string GetXsdForXml(string xml)
        {
            //get the xsd for the xml
            XmlReader xr = XmlReader.Create(new StringReader(xml));

            //infer the schema from the xml loaded in the XmlReader
            XmlSchemaInference schema = new XmlSchemaInference();
            var schemaSet = schema.InferSchema(xr);

            //grabd the xsd as a string
            StringBuilder xsd = new StringBuilder();

            //iterate through the schemas
            foreach (XmlSchema s in schemaSet.Schemas())
            {
                //write each XmlSchema to a string
                using (var ms = new MemoryStream())
                {
                    s.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);

                    using (var sr = new StreamReader(ms))
                    {
                        xsd.Append(sr.ReadToEnd());
                    }
                }
            }

            return xsd.ToString();
        }

        /// <summary>
        /// Author: Mike Barksdale
        /// Helper method to get the XML declaration.
        /// </summary>
        /// <returns>A string representing the standard XML declaration</returns>
        public static string GetXmlDeclaration()
        {
            return "<?xml version=\"1.0\"?>";
        }

        public static string CleanSql(string sql)
        {
            sql = sql.Replace(";", string.Empty);

            //only work with the select statement
            var selectStatement = sql.Substring(0, sql.ToUpper().IndexOf("FROM"));

            var cleanSql = new StringBuilder(selectStatement);

            //remove attribute symbols
            cleanSql.Replace("@", string.Empty);

            //remove xml symbols ("<", ">") and opening tag name
            var splitSql = cleanSql.ToString().Split(' ');

            var builtSql = new StringBuilder();

            foreach (var token in splitSql)
            {
                if (!token.StartsWith("<"))
                    builtSql.Append(token + " ");
            }

            //remove the last space
            builtSql.Remove(builtSql.Length - 1, 1);

            builtSql.Replace(">", string.Empty);

            return builtSql.Append(sql.Substring(sql.ToUpper().IndexOf("FROM"))).ToString();
        }
    }
}